package com.youlai.boot.gym.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.youlai.boot.system.model.bo.VisitCount;
import com.youlai.boot.system.model.bo.VisitStatsBO;
import com.youlai.boot.system.model.vo.VisitStatsVO;
import com.youlai.boot.system.model.vo.VisitTrendVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.gym.mapper.AccessLogsMapper;
import com.youlai.boot.gym.service.AccessLogsService;
import com.youlai.boot.gym.model.entity.AccessLogs;
import com.youlai.boot.gym.model.form.AccessLogsForm;
import com.youlai.boot.gym.model.query.AccessLogsQuery;
import com.youlai.boot.gym.model.vo.AccessLogsVO;
import com.youlai.boot.gym.converter.AccessLogsConverter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 出入日志服务实现类
 *
 * @author hxc
 * @since 2025-06-01 12:37
 */
@Service
@RequiredArgsConstructor
public class AccessLogsServiceImpl extends ServiceImpl<AccessLogsMapper, AccessLogs> implements AccessLogsService {

    private final AccessLogsConverter accessLogsConverter;

    private final AccessLogsMapper accessLogMapper;
    /**
    * 获取出入日志分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<AccessLogsVO>} 出入日志分页列表
    */
    @Override
    public IPage<AccessLogsVO> getAccessLogsPage(AccessLogsQuery queryParams) {
        Page<AccessLogsVO> pageVO = this.baseMapper.getAccessLogsPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取出入日志表单数据
     *
     * @param id 出入日志ID
     * @return 出入日志表单数据
     */
    @Override
    public AccessLogsForm getAccessLogsFormData(Long id) {
        AccessLogs entity = this.getById(id);
        return accessLogsConverter.toForm(entity);
    }
    
    /**
     * 新增出入日志
     *
     * @param formData 出入日志表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveAccessLogs(AccessLogsForm formData) {
        AccessLogs entity = accessLogsConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新出入日志
     *
     * @param id   出入日志ID
     * @param formData 出入日志表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateAccessLogs(Long id,AccessLogsForm formData) {
        AccessLogs entity = accessLogsConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除出入日志
     *
     * @param ids 出入日志ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteAccessLogss(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的出入日志数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    @Override
    public Integer getPeopleInGym() {
// 获取今天的开始和结束时间
        LocalDateTime startOfDay = LocalDateTime.now().with(LocalTime.MIN);
        LocalDateTime endOfDay = LocalDateTime.now().with(LocalTime.MAX);

        // 查询进入人数
        Long enterCount = accessLogMapper.selectCount(
                new LambdaQueryWrapper<AccessLogs>()
                        .eq(AccessLogs::getAccessType, 1)  // 进入类型
                        .between(AccessLogs::getAccessTime, startOfDay, endOfDay)
                        .eq(AccessLogs::getIsDeleted, false)
        );

        // 查询离开人数
        Long exitCount = accessLogMapper.selectCount(
                new LambdaQueryWrapper<AccessLogs>()
                        .eq(AccessLogs::getAccessType, 2)  // 离开类型
                        .between(AccessLogs::getAccessTime, startOfDay, endOfDay)
                        .eq(AccessLogs::getIsDeleted, false)
        );

        // 计算差值，确保结果 >= 0
        return Math.max(0,  Math.toIntExact(enterCount - exitCount));

    }


    /**
     * 获取访问趋势
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return
     */
    @Override
    public VisitTrendVO getVisitTrend(LocalDate startDate, LocalDate endDate) {
        VisitTrendVO visitTrend = new VisitTrendVO();
        List<String> dates = new ArrayList<>();
        // 获取日期范围内的日期
        while (!startDate.isAfter(endDate)) {
            dates.add(startDate.toString());
            startDate = startDate.plusDays(1);
        }
        visitTrend.setDates(dates);

        // 获取访问人数和访问量的统计数据
        List<VisitCount> pvCounts = this.baseMapper.getPvCounts(dates.get(0) + " 00:00:00", dates.get(dates.size() - 1) + " 23:59:59");
        List<VisitCount> uvCounts = this.baseMapper.getUvCounts(dates.get(0) + " 00:00:00", dates.get(dates.size() - 1) + " 23:59:59");

        // 将统计数据转换为 Map
        Map<String, Integer> pvMap = pvCounts.stream().collect(Collectors.toMap(VisitCount::getDate, VisitCount::getCount));
        Map<String, Integer> ipMap = uvCounts.stream().collect(Collectors.toMap(VisitCount::getDate, VisitCount::getCount));

        // 匹配日期和访问量/访问 IP 数
        List<Integer> pvList = new ArrayList<>();
        List<Integer> uvList = new ArrayList<>();

        for (String date : dates) {
            pvList.add(pvMap.getOrDefault(date, 0));
            uvList.add(ipMap.getOrDefault(date, 0));
        }

        visitTrend.setPvList(pvList);
        visitTrend.setIpList(uvList);

        return visitTrend;


    }

    /**
     * 访问量统计
     */
    @Override
    public VisitStatsVO getVisitStats() {
        VisitStatsVO result = new VisitStatsVO();

        // 访客数统计(UV)
        VisitStatsBO uvStats = this.baseMapper.getUvStats();
        if(uvStats!=null){
            result.setTodayUvCount(uvStats.getTodayCount());
            result.setTotalUvCount(uvStats.getTotalCount());
            result.setUvGrowthRate(uvStats.getGrowthRate());
        }

        // 浏览量统计(PV)
        VisitStatsBO pvStats = this.baseMapper.getPvStats();
        if(pvStats!=null){
            result.setTodayPvCount(pvStats.getTodayCount());
            result.setTotalPvCount(pvStats.getTotalCount());
            result.setPvGrowthRate(pvStats.getGrowthRate());
        }

        return result;
    }


}
